package com.deloitte.snap.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.deloitte.snap.util.CommonUtil;

public abstract class AbstractDAO<T,S extends Serializable>  extends HibernateDaoSupport{

	private  Class<T> persistentClass;
    public AbstractDAO() { 
    	super();
    	persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public void saveOrUpdate(T obj) {
        getHibernateTemplate().saveOrUpdate(obj);
    }

    public void delete(T obj) {
        getHibernateTemplate().delete(obj);
    }
    public void delete(S id) {
    	 delete(find(id));
    }

    public T find(S id) {
        return (T) getHibernateTemplate().load(persistentClass, id);
    }

    public List<T> findAll() {
        return getHibernateTemplate().find("from " + persistentClass.getName());
    }
    
    public List<T> findQuery(String condition) {
    	StringBuffer query = new StringBuffer();
    	query.append("from " + persistentClass.getName()).append(" where 1= 1");
    	if(!CommonUtil.isEmpty(condition)){
    		query.append(" and ").append(condition);
    	}
        return getHibernateTemplate().find(query.toString());
    }
    
    public List executeQuery(String query) {
        return getHibernateTemplate().find(query);
    }
}

